import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
} from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/modules/user"; // 引入vuex方法

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // url = base url + request url
  // withCredentials: true, //
  timeout: 25000, // 超时实际
});
service.interceptors.request.use(
  (config: any) => {
    const userStore = useUserStore();
    const token = userStore.getToken;
    if (typeof token !== "undefined") {
      config!.headers!["Admin-Token"] = token;
    }
    return config;
  },
  (error: AxiosError) => {
    console.log(error); 
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response: AxiosResponse<any>) => {
    const res = response.data;
    console.log(res)
    if (res.code == 200) {
      return res;
    } else {
      ElMessage.error(res.msg);
      return Promise.reject(res);
    }
  },
  (error) => {
    ElMessage({
      message: error.message.includes("timeout")
        ? "网络延迟,请稍后再试!"
        : error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
